-- 每日累充
local Util = require("common.Util")
local CommonDB = require("common.CommonDB")
local Log = require("common.Log")
local PresentExcel = require("excel.present")
local MailExcel = require("excel.mail")
local MailManager = require("mail.MailManager")
local Msg = require("core.Msg")
local ObjHuman = require("core.ObjHuman")
local BagLogic = require("bag.BagLogic")
local Grid = require("bag.Grid")
local SceneHandler = require("scene.Handler")

local function getConfig()
    local subDay = CommonDB.getServerOpenDay()
	if subDay == nil then
		return 
	end	
	if subDay <= 7 then
	    -- 开服首周
	    return PresentExcel.dailyLeichong[1]
	else
		-- 开服第二周和以后
		return PresentExcel.dailyLeichong[2]
	end
end

function isOpen(human)
	if true then
		return
	end

	if not SceneHandler.canCharge(human) then
		return
	end

	local config = getConfig()
	if config == nil then return end
	
	return true
end

function query(human)
	local config = getConfig()
	if config == nil then return end

    local now = os.time()	
	local msgRet = Msg.gc.GC_DAILY_LEICHONG_QUERY
	msgRet.sec = Util.getDayStartTime(now) + 24 * 3600 - now
	
	-- 今日累充金额
	ObjHuman.updateDaily(human)
	local nowDailyCharge = human.db.topupAcountDaily or 0
	
	for i = 1, #config.pay do
		msgRet.weekPay[i].id = i
		msgRet.weekPay[i].cur = nowDailyCharge
		msgRet.weekPay[i].max = config.pay[i]
		msgRet.weekPay[i].desc = Util.format(config.desc, config.pay[i])
		msgRet.weekPay[i].reward[0] = #(config.reward[i])
		for j = 1, msgRet.weekPay[i].reward[0] do
			local itemID = config.reward[i][j][1]
			local itemCnt = config.reward[i][j][2]
			Grid.makeItem(msgRet.weekPay[i].reward[j], itemID, itemCnt)
		end
	end
	msgRet.weekPay[0] = #config.pay
	Msg.send(msgRet, human.fd)
end


function charge(human, price)
	if isOpen(human) ~= true then
		return
	end

    active(human, price)
end

function active(human, price)
	local config = getConfig()
	if config == nil then return end
	
	local nowDailyCharge = human.db.topupAcountDaily
	local lastDailyCharge = nowDailyCharge - price

	local dailyLeiChong = human.db.dailyLeiChong
	for i = 1, #config.pay do
		if not dailyLeiChong or not dailyLeiChong[i] then
			local needPay = config.pay[i]
			if needPay <= nowDailyCharge and needPay > lastDailyCharge then
				human.db.dailyLeiChong = human.db.dailyLeiChong or {}
				human.db.dailyLeiChong[i] = i
				
				-- 发放奖励
				local items = { }
				for z, v in ipairs(config.reward[i])  do
				   items[z] = { v[1],  v[2] }
				end
					
				--[[local title = MailExcel.mail[62].title
				local content = Util.format(MailExcel.mail[62].content, config.pay[i]) 
				local senderName = MailExcel.mail[62].senderName
				MailManager.add(MailManager.SYSTEM, human.db._id, title, content, items, senderName)]]
			end
		end
	end	
end


